package com.tuomaxu.thread;

import com.tuomaxu.pojo.Mapper;
import com.tuomaxu.pojo.Request;
import com.tuomaxu.pojo.Response;
import com.tuomaxu.servlet.HttpServlet;
import com.tuomaxu.utils.ServerXmlParserUtil;

import java.net.Socket;
import java.util.Map;

public class MyRequestProcessor extends Thread{
    private Socket socket;
    private Mapper mapper;

    public MyRequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            //获取输入流，构造request对象
            Request request = new Request(socket.getInputStream());

            //获取输出流，构造response对象
            Response response = new Response(socket.getOutputStream());

            //通过url获取请求处理的servlet
            HttpServlet httpServlet = mapper.getServletByUrl(request.getUrl());
            //如果能获取到，认为是动态
             if(httpServlet != null){
                httpServlet.service(request,response);
            }else {
                //不能获取到，任务是静态
                response.write(ServerXmlParserUtil.appBase+request.getUrl());
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
